import { Card, Form, Input, Button, Checkbox, message } from 'antd'
import logo from '@/assets/logo.png'
import './index.scss'
import { useProfile } from '@/store/profile'
import { reqLogin } from '@/api/login'
import { useNavigate } from 'react-router-dom'

type FieldType = {
  username?: number
  password?: string
  remember?: number
}

const Login = () => {
  const navigate = useNavigate()

  const onFinish = async (values: FieldType) => {
    try {
      const res = await reqLogin({ mobile: values.username!, code: values.password! })
      useProfile.saveToken(res.data.token)
    } catch (error) {
      message.error((error as any).response?.data?.message)
    }

    // 提示登录成功
    message.success('登录成功')
    navigate('/', { replace: true })
  }
  return (
    <div className="login">
      <Card className="login-container">
        <img className="login-logo" src={logo} alt="" />
        {/* 登录表单 */}
        <Form
          initialValues={{ remember: true, username: 13811111111, password: '246810' }}
          validateTrigger={['onBlur', 'onChange']}
          onFinish={onFinish}
        >
          <Form.Item<FieldType>
            name="username"
            rules={[
              { required: true, message: '请输入手机号' },
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '手机号格式错误',
                validateTrigger: 'onBlur'
              }
            ]}
          >
            <Input size="large" placeholder="请输入手机号" />
          </Form.Item>
          <Form.Item name="password" rules={[{ required: true, message: '密码不能为空' }]}>
            <Input.Password size="large" placeholder="请输入密码" />
          </Form.Item>
          <Form.Item<FieldType> valuePropName="checked" name="remember">
            <Checkbox className="login-checkbox-label">
              我已阅读并同意「用户协议」和「隐私条款」
            </Checkbox>
          </Form.Item>
          <Form.Item<FieldType>>
            <Button type="primary" htmlType="submit" size="large" block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Login
